const {createUser, getUserInfo} = require('../service/user.server')
const {userFormateErr, userAlreadyErr, loginUser, passwordErr} = require("../errType/err.type")
var bcrypt = require('bcryptjs');
const validator = async (ctx, next) => {
    const {user_name, password} = ctx.request.body
    // ！不合法
    if (!user_name || !password) {
        ctx.status = 400
        ctx.app.emit('err', userFormateErr, ctx)
        return
    }
    await next()
}
const verfyUser = async (ctx, next) => {
    const {user_name, password} = ctx.request.body;
    const res = await getUserInfo({user_name})
    // 合理
    if (res) {
        ctx.status = 409
        ctx.app.emit('err', userAlreadyErr, ctx)
        return
    }
    await next()
}
// 密码加密
const crpytPassword = async (ctx, next) => {
    const {password} = ctx.request.body
    const salt = bcrypt.genSaltSync(10);
    // 密文
    const hash = bcrypt.hashSync(password, salt);
    ctx.request.body.password = hash
    await next()
}
const verfyLogin = async (ctx, next) => {
//     验证用户是否存在
    const {user_name, password} = ctx.request.body
    const res = await getUserInfo({user_name})
    if (!res) return ctx.app.emit('err', loginUser, ctx)
//     判断密码是否匹配
    if (!bcrypt.compareSync(password, res.password)) {
        return ctx.app.emit('err', passwordErr, ctx)

    }

    await next()
}
module.exports = {
    validator, verfyUser, crpytPassword, verfyLogin
}